
var layopen = function(content){
	layer.open({
	  	title:'更新表单项'
		,content: content
    	,area: ['700px', '700px']
	    ,scrollbar: false
	  	,btn: ['确认', '取消']
		,yes: function(index,layero){ //确认
		  	var data = $(layero).find("form").serializeJSON();
		  	if(verifyCode(data)){
		  		commitUpdate(data);
		  	}
		}
});
}

$("body").undelegate("input[lay-type='images']","click").delegate("input[lay-type='images']","click",function(){
	var data_id = $(this).attr("data_id");
	var file_type = $(this).attr("file_type");
	upload(data_id,file_type);
}); 


var upload = function(data_id , file_type){
	var allow_format;
	if("image_div"==file_type){
		allow_format = 'jpg|png|gif';
	}else if("excel"==file_type){
		allow_format = 'xls|xlsx';
	}else if("word" == file_type){
		allow_format = 'doc|docx';
	}else if("pdf" == file_type){
		allow_format = 'pdf';
	}else if("dwg" == file_type){
		allow_format = 'dwg';
	}
	layui.upload({
		  url: base+'/projectCenter/uploadFileApi/uploadFile/'+project_id
		  ,type:'file'
		  ,ext:allow_format
		  ,success: function(res){
			  if(res.code == '0'){
				  var original_file_name = res.original_file_name;
				  var file_id = res.file_id;
				  var image_src = res.image_src;
				  $("img[data_id='"+data_id+"']").attr("src",image_src);
				  $("input[name='"+data_id+"']").val(file_id);
				  layer.msg(res.msg, {icon: 1,time:2000});
			  }else{
				  layer.msg(res.msg, {icon: 2,time:2000});
			  }
		  }
	});
}

//验证方法
var verifyCode = function(data){
	var flag = true;
	$.each(data,function(index,value){
		if(value == "" || value == null){
			var obj = $("input[name='"+index+"']");
			obj.focus();
			layer.tips('请填写此字段!', obj);
			flag = false;
			return false;
		}
	});
	return flag;
}

//提交更新方法
var commitUpdate = function(data){
	$.post(base+"/projectCenter/businessdata/updateMentionDataByTable/"+mention_id,data,
		function (data,status){
		if(data!=""&&data!=null){
			if(data.statusCode == 0){
				layer.msg('更新成功', {icon: 1,time:2000});
			}else{
				layer.msg(data.message, {icon: 2,time:2000});
			}
		}else{
			layer.msg('更新失败!', {icon: 2,time:2000});
		}
		initData(1);
		})
}

function addObj(){
	var contentDiv = function(){
		var content;
		var data={
				"title":{
				},"text":{
				},"input":{
				},"input_init":{
				}
		};
	    var data_input = data.input;//弹出层表单类型
	    var data_text = data.text;
		delete head_data_list.operation; //删除操作字段
		delete head_data_list.id;//删除主键字段
		data.title = head_data_list; //表头渲染到弹出层
		//赋值操作
		$.each(data.title,function(index,value){
			data_input[index] = "text";
			data_text[index] = "";
		});
		data_input["project_id"] = "hidden";
		data_text["project_id"] = project_id;
		var getDiv =  dc_update.innerHTML;
		laytpl(getDiv).render(data, function(html){
			content = html;
		}); 
		return content;
	}
	layopen(contentDiv());
}

var delObj = function(obj){
	   layer.confirm('确认删除?',{btn : [ '确定', '取消' ]},function(index){
		   layer.close(index);
		   var id = obj.id;
			$.post(base+"/projectCenter/businessdata/delMentionDataById/"+mention_id+"/"+id,{},
				function (data,status){
				if(data!=""&&data!=null){
					if(data.statusCode == 0){
						layer.msg('删除成功', {icon: 1,time:2000});
					}else{
						layer.msg(data.message, {icon: 2,time:2000});
					}
				}else{
					layer.msg('删除失败!', {icon: 2,time:2000});
				}
				initData(1);
				})
	   });
}

  var updateObj = function(obj){
  	var contentDiv = function(obj){
  		var content;
  		var data={
  				"title":{
  				},"text":{
  				},"input":{
  				},"input_init":{
  				}
  		};
  	    var data_input = data.input;//弹出层表单类型
  		delete head_data_list.operation; //删除操作字段
  		data.title = head_data_list; //表头渲染到弹出层
  		data.text = obj;
  		//赋值操作
  		$.each(data.title,function(index,value){
  			data_input[index] = "text";
  		});
  		var getDiv =  dc_update.innerHTML;
  		laytpl(getDiv).render(data, function(html){
  			content = html;
  		}); 
  		return content;
  	}
  	layopen(contentDiv(obj));
  }
  
  var celledit = function (obj,key,value,that,type,val) {
	    if (type=='text') {
	        var t_name = $.trim($("#t_name").val());
	        if(!$(that).is('.input')){
	            $(that).addClass('input').html('<input type="text" id="'+key+'" value="'+ value +'" />').find('input').focus().blur(function(){
	                if (value!=$("#"+key).val()) {
	                    $.ajax({
	                        url:base+"/projectCenter/commonupdate/updateOneField/",
	                        data:{"record_id":obj.id,"t_name":t_name,"field_name":key,"value":$("#"+key).val()},
	                        success:function(data,status){
	                            initData(pnum);
	                        }
	                    });
	                }
	                $(that).removeClass('input').html($("#"+key).val());
	            });
	        }
	    } else if (type=='select') {
	        var t_name = $.trim($("#t_name").val());
	        var str = val.split("-");
	        var soption = "";
	        for (var i=0;i<str.length;i++) {
	            if (""!=str[i]) {
	                if (value==str[i].split("_")[1]) {
	                    soption+="<option value='"+str[i].split("_")[0]+"' selected>"+str[i].split("_")[1]+"</option>";
	                } else {
	                    soption+="<option value='"+str[i].split("_")[0]+"'>"+str[i].split("_")[1]+"</option>";
	                }
	            }
	        }
	        if(!$(that).is('.select')){
	            var html = "<select id='"+key+"' name='"+key+"' style='display:block;'>"+soption+"</select>";
	            $(that).addClass('select').html(html).find('select').focus().blur(function(){
	                if (value!=$("#"+key).val()) {
	                    $.ajax({
	                        url:base+"/projectCenter/commonupdate/updateOneField/",
	                        data:{"record_id":obj.id,"t_name":t_name,"field_name":key,"value":$("#"+key).val()},
	                        success:function(data,status){
	                            initData(pnum);
	                        }
	                    });
	                }
	                $(that).removeClass('select').html($("#"+key).val());
	            });
	        }
	    }

	}
	  
  $("body").delegate("#downExcelModel","click",function(){
		var url = base+"/projectCenter/excelApi/exportExcelModel/"+mention_id;
		window.open(url,"_self");
		return false;
	});

$("body").undelegate("#initJydcss","click").delegate("#initJydcss","click",function(){
    $.ajax({
        url:base+"/projectCenter/businessdata/initJydcss/"+project_id+"/"+$.trim($("#t_name").val()),
        data:{},
        success:function(data,status){
            if(data!=""&&data!=null){
                if(data.statusCode == 0){
                    layer.msg('计算成功', {icon: 1,time:2000});
                }else{
                    layer.msg(data.message, {icon: 2,time:2000});
                }
            }else{
                layer.msg('计算失败!', {icon: 2,time:2000});
            }
            initData(1);
        }
    });
});

$("body").undelegate("#initJyjwss","click").delegate("#initJyjwss","click",function(){
    $.ajax({
        url:base+"/projectCenter/businessdata/initJyjwss/"+project_id+"/"+$.trim($("#t_name").val()),
        data:{},
        success:function(data,status){
            if(data!=""&&data!=null){
                if(data.statusCode == 0){
                    layer.msg('计算成功', {icon: 1,time:2000});
                }else{
                    layer.msg(data.message, {icon: 2,time:2000});
                }
            }else{
                layer.msg('计算失败!', {icon: 2,time:2000});
            }
            initData(1);
        }
    });
});



  $("div").undelegate().delegate("#submit_btn","click",function(){
	 	var data_json = submitCheck();
	 	//alert(JSON.stringify(data_json));
		$.post(base+"/projectCenter/businessdata/updateMentionDataByTable/"+mention_id,data_json,
			function (data,status){
			if(data!=""&&data!=null){
				if(data.statusCode == 0){
					layer.msg('更新成功', {icon: 1,time:2000});
				}else{
					layer.msg(data.message, {icon: 2,time:2000});
				}
			}else{
				layer.msg('更新失败!', {icon: 2,time:2000});
			}
			　　setTimeout(initData,2000);
			});
		return false;
	 });

$("body").undelegate("div[lay-skin='_switch']","click").delegate("div[lay-skin='_switch']","click",function(){
	var bool = $.trim($(this).children("em").text());
	var field_name = $(this).prev().attr("name");
	if("是" == bool){
		//显示
		if("zhgqsfphgdcz" == field_name){
			$("select[name='zhgqgdczdzc']").parent().parent().show();
		}
		if("zhgqsfszgcck" == field_name){
			$("input[name='zhgqgccksfszqzj']").parent().parent().show();
		}
	}else if("否" == bool){
		//隐藏
		if("zhgqsfphgdcz" == field_name){
			$("select[name='zhgqgdczdzc']").parent().parent().hide();
		}
		if("zhgqsfszgcck" == field_name){
			$("input[name='zhgqgccksfszqzj']").parent().parent().hide();
		}
	}
})

//表单提交校验
var submitCheck = function(){
	var data_json = {};
	var _name = "";
	var _value = "";
	$.each($("[name]"),function(index,value){
		var name = $(this).attr("name");
		var type =$(this).attr("type");
		var value = "";
		if("layui-upload-iframe" != name && "file" != name){
			if($(this).attr("lay-skin") == "switch"){
				value = $(this).next().children("em").text()=="是"?"on":"off";
		 		data_json[name] = value;
			}else if("checkbox" == type){
				if(_name == ""){
					_name = name;
				}
				if($(this).next().hasClass("layui-form-checked") && _name == name){
					_value = _value + $(this).attr("title") + ",";
				}else if(_name != name){
					_name = "";
					_value = "";
				}
				data_json[name] = _value;
			}else{
				value = $(this).val();
				data_json[name] = value;
			}
		}
	});
	return data_json;
}

//初始化状态,
var initializeFunction = function(){
	var state_gdcz = $.trim($("input[name='zhgqsfphgdcz']").next().children("em").text());
	if("是" == state_gdcz){
		$("select[name='zhgqgdczdzc']").parent().parent().show();
	}else if("否" == state_gdcz){
		$("select[name='zhgqgdczdzc']").parent().parent().hide();
	}
	var state_gcck = $.trim($("input[name='zhgqsfszgcck']").next().children("em").text());
	if("是" == state_gcck){
		$("input[name='zhgqgccksfszqzj']").parent().parent().show();
	}else{
		$("input[name='zhgqgccksfszqzj']").parent().parent().hide();
	}
}
	  
var pnum=1;
var initData = function(num){
	var url = base+"/projectCenter/businessdata/mentionDataManage";
	var param = {
			page_num:num,
			page_size:"6",
			mention_data_id:mention_id,
			project_id:project_id
	};
	$.ajax({
        url: url,
        data: param,
        success: function (data, textStatus, jqXHR) {
        	if(data != null){
        		if(data.form != null){
        			layui.use(['layer', 'form', 'element'], function(){
        				  var layer = layui.layer
        				  ,form = layui.form()
                    var html = data.form;
                	$("#view").html("");
                	$("#view").html("<form class='layui-form' style='float:left;'>"+html+"</form>");
                	form.render();
                	initializeFunction();
                	upload();
        			});
        		}else{
        			showButton();
    	        	var pageCount = data.data_list.pager.pageCount;
    	        	var dataObj ={
    	        			"list":data.data_list.list, 
    	         			"dataTool":{
    	         				"title":{
    	            			},
                                "editField":{},
    	            			"titleCheckbox":false,
    							"btn":[{"event":"updateObj","name":"编辑"},
    							       {"event":"delObj","name":"删除"}]
    						}
    		  		};
    	        	var title_list = data.title_list;
    	        	var title = dataObj.dataTool.title;

                    var edit = dataObj.dataTool.editField;
    	        	$.each(title_list,function(index,value){
    	        		var field_name = title_list[index].field_name;
    	        		var field_comment = title_list[index].field_comment;
                        if (field_name!="id"&& field_name!="project_id") {
                            title[field_name] = field_comment;
                            var editField = {};
                            editField["field"] = field_name;
                            editField["type"] = "text";
                            edit[index]=editField;
                        }
    	        	});
                    edit = JSON.stringify(edit);
    	        	head_data_list = title; //将表头作为全局表里保存以便编辑操作
    	        	title.operation = "操作";
    	        	showPageTable('view', dataObj,num,pageCount,"initData");
        		}
        	}
        },
        error: function () {
        }
    });
	
}


$("body").delegate("input[lay-type='file']","click",function(){
	uploadFile();
}); 

var showButton = function(){
	var button_html = ' <div class="btn-team">'+
		              ' <input name="file" lay-type="file" class="layui-upload-file" type="file"  lay-title="上传资料">'+
		              ' <button class="btn btn-default" id="addData" onclick="addObj();">新增记录</button>'+
		              ' <button class="btn btn-default" id="downExcelModel">下载模板</button>';
    var t_name = $.trim($("#t_name").val());
    if (t_name=="dc_mention_jydcss") {
		button_html+='<button class="btn btn-default" id="initJydcss">一键初始化</button>';
	}
    if (t_name=="dc_mention_JYJWSS") {
        button_html+='<button class="btn btn-default" id="initJyjwss">一键初始化</button>';
    }
    if(t_name == "dc_mention_FXJLKLCDSB" || t_name == "dc_mention_JDLKLCDSB" || t_name == "dc_mention_ZZFLKLCDSB" || t_name == "dc_mention_czjwsssrb" || t_name == "dc_mention_jwlcdsb"){
    	button_html+= ' <button class="btn btn-default" onclick="openDcsssjk()">动车设施数据库</button> '+
    		          ' <button class="btn btn-default" onclick="openCs()">测算</button> ';
    }
	button_html+="</div>";
	$(".btn-team").remove();
	$("#div_content").prepend(button_html);
	//显示上传按钮后初始化上传操作
	uploadFile();
}

//打开动车设施数据库
var openDcsssjk = function(){
	open(base+"/resource/index?parent_id=0003&children_id=00030002");
}

//打开测算页面
var openCs = function(){
	open("https://www.huoche.net/tools/gongli-wuhan-nanning/");
}

var uploadFile = function(){
	layui.upload({
		  url: base+'/projectCenter/excelApi/uploadExcel?mention_data_id='+mention_id+'&project_id='+project_id
		  ,title: '请上传excel文件'
		  ,ext: 'xls|xlsx' //那么，就只会支持这两种格式的上传。注意是用|分割。
		  ,success: function(res){
		    if(res.statusCode == 0){
				layer.msg(res.message, {
					icon : 1
				});
		    }else{
				layer.msg(res.message, {
					icon : 5
				});
		    }
		    initData(1);
		  }
	});
	return false;
}

$(document).ready(function(){
	initData(1);
});

